import {
  getSearchData
} from '../network/header.js';

$(function() {
  class Search {
    constructor() {
      //获取搜索框
      this.search_input = $('.search-input');
      //获取标题搜索列表
      this.title_list = $('.search-menu .title-list');
      //获取搜索内容列表
      this.content_list = $('.search-menu .content-list');
      //获取搜索按钮
      this.search_btn = $('.search-btn');
      this.bindEvent();
    }
    //绑定事件
    bindEvent() {
      let _this = this;
      this.search_input.on('input focus', function() {
        console.log($(this));
        if($(this).val().trim()) {
          $(this).siblings('.search-menu').css('display', 'block');
          getSearchData($(this).val(), (res) => {
            _this.renderSearchMenu(res);
          })
        }else {
          $(this).siblings('.search-menu').css('display', 'none');
        }
      });

      this.search_btn.on('click', function() {
        location.href = `https://list.mogu.com/search/goods?q=${_this.search_input.val()}&title=${_this.search_input.val()}`;
      });
    }

    //渲染搜索菜单
    renderSearchMenu(res) {
      let data = res.result.list;
      let titlestr = ``;
      let contentstr = ``;
      for(let i=0; i<data[0].list.length; i++) {
        titlestr += `
          <li ${data[0].list[i].valid ? "class='valid'" : ""}>
            <i style="background: #999999 url('${data[0].list[i].icon}') no-repeat center; 
            background-size: 12px 11px;"></i>
            <span class='title-count'>${data[0].list[i].total}</span><span class="title-text">${data[0].list[i].desc}</span>
          </li>
        `
      }
      for(let i=1; i<data.length; i++) {
        contentstr += `
          <li><a href="${data[i].link}">${data[i].tag}</a></li>
        `;
      }
      this.title_list.html(titlestr);
      this.content_list.html(contentstr);
    }
  }
  new Search();
});